package com.morningstar.system.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.morningstar.system.controller.result.FileUploadResult;
import com.morningstar.system.dao.entity.SysFile;
import com.morningstar.system.dao.mapper.SysFileMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 系统文件 服务实现类
 *
 * @author yanglianshan
 * @since 2024-04-07
 */
@Slf4j
@Service
public class SysFileService extends ServiceImpl<SysFileMapper, SysFile> {

    @Resource
    private SysFileMapper sysFileMapper;

    @Resource
    private FileOperate fileOperate;

    public FileUploadResult uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        String filePath = fileOperate.upload(file);
        SysFile sysFile = new SysFile();
        sysFile.setFileName(file.getOriginalFilename());
        sysFile.setFileSize(file.getSize() + "");
        sysFile.setFileType(file.getContentType());
        sysFile.setFilePath(filePath);
        sysFileMapper.insert(sysFile);
        FileUploadResult fileUploadResult = new FileUploadResult();
        fileUploadResult.setFileId(sysFile.getFileId());
        fileUploadResult.setPreviewUrl(getUrlPrefix() + filePath);
        return fileUploadResult;
    }

    public List<SysFile> listFile(List<Long> fileIds) {
        return sysFileMapper.selectBatchIds(fileIds);
    }

    public String getUrlPrefix() {
        return fileOperate.getUrlPrefix();
    }
}
